package log

import (
	"fmt"
	"strings"
	"time"
)

type TextFormatter struct {
}

func (t *TextFormatter) Format(param *LoggingFormatParam) string {
	now := time.Now()

	fieldsString := ""

	if param.LoggerFields != nil {
		// name=xx,age=xx
		var sb strings.Builder
		var count = 0
		var lens = len(param.LoggerFields)
		for k, v := range param.LoggerFields {
			_, _ = fmt.Fprintf(&sb, "%s=%v", k, v)
			if count < lens-1 {
				sb.WriteString(",")
				count++
			}
		}
		fieldsString = sb.String()
	}

	var msgInfo = "\n msg: "
	if param.Level == LevelError {
		msgInfo = "\n Error Cause By: "
	}
	if param.Color {
		// 要带颜色 error的颜色 为红色， info为绿色 debug 为蓝色
		levelColor := t.LevelColor(param.Level)
		msgColor := t.MsgColor(param.Level)
		return fmt.Sprintf("%s[msgo]%s %s%v%s | level=%s%s%s%s%s%v%s %s\n",
			yellow, reset,
			blue, now.Format("2006/01/02-15:04:05"), reset,
			levelColor, param.Level.Level(), reset,
			msgColor, msgInfo, param.Msg, reset,
			fieldsString,
		)
	}
	return fmt.Sprintf("[msgo] %v | level=%s%s%v %s\n",
		now.Format("2006/01/02 - 15:04:05"),
		param.Level.Level(), msgInfo, param.Msg,
		fieldsString,
	)
}

func (t *TextFormatter) LevelColor(level LoggerLevel) string {
	switch level {
	case LevelDebug:
		return blue
	case LevelInfo:
		return green
	case LevelError:
		return red
	default:
		return cyan
	}
}
func (t *TextFormatter) MsgColor(level LoggerLevel) string {
	switch level {
	case LevelDebug:
		return ""
	case LevelInfo:
		return ""
	case LevelError:
		return red
	default:
		return cyan
	}
}
